package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrOctetString;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Optional;

public class SecurityData extends AxdrType {
    private ByteBuffer dataCode = null;
    private RN rn = null;
    private AxdrOctetString sign = null;

    public SecurityData() {
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = ByteBuffer.wrap(dataCode);
    }

    public void setAll(RN rn, AxdrOctetString sign) {
        this.rn = rn;
        this.sign = sign;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.rn = new RN();
        codeLength += this.rn.decode(input);
        this.sign = new AxdrOctetString();
        codeLength += this.sign.decode(input);
        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.remaining();
            while (this.dataCode.hasRemaining()) {
                output.write(this.dataCode.get());
            }
        } else {
            if (this.rn != null && this.sign != null) {
                codeLength = 0;
                codeLength += this.sign.encode(output);
                codeLength += this.rn.encode(output);
            } else {
                throw new IllegalArgumentException("sign or rn is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = ByteBuffer.wrap(revOStream.getArray());
    }

    @Override
    public String toString() {
        if (this.rn != null && this.sign != null) {
            return "sequence: {" + "rn: " + this.rn + ", sign: " + this.sign + "}";
        } else {
            return "sign or rn is null";
        }
    }
}



